Page({
  data: {
    fundInfoList:[],
    hasFundCode:false,
  
 },
 onLoad() {
   console.log(this.data.items)
   // this.getFundList()
 },
 onPullDownRefresh() {
   this.getFundList();
   console.log('onPullDownRefresh', new Date());
 },
 stopPullDownRefresh() {
   my.stopPullDownRefresh({
     complete(res) {
       console.log(res, new Date())
     }
   })
 },
 onShow(){
   this.getFundList();
 },



getFundList(){
   const {data} = my.getStorageSync({key:'fundList'});
   console.log(data)
   var that=this;
   this.setData({
    fundInfoList:[],
    hasFundCode:false
   })
  
   if(data){

    const res=  this.getFundSync(data);
  
    console.log({"code列表":JSON.stringify(data)})
    
    console.log({"同步请求结果":JSON.stringify(res)})
     
     this.stopPullDownRefresh()

   }

   
 },

 

 async  getFundSync(array) {
  const resultArray = [];
  console.log({"传入的数组":array})

  for (let i = 0; i < array.length; i++) {
    try {
      const result = await this.getFund(array[i]); // 发起请求的函数
      resultArray[i] = result; // 根据索引将结果存入结果数组
      console.log("第"+i+"次循环")
    } catch (error) {
      // 处理请求错误
      console.error(`Request failed for element at index ${i}:`, error);
      resultArray[i] = null; // 如果请求失败，可以将结果设为 null 或其他适当的值
    }
  }

  return resultArray;
},

getFund(fundCode) {
  return new Promise((resolve, reject) => {
    // 在这里执行您的请求逻辑，并在请求成功时调用 resolve(result)，请求失败时调用 reject(error)
    const fundUrl='https://fundgz.1234567.com.cn/js/'+fundCode+'.js' 
    var resjson;
    my.request({url: fundUrl,method: 'GET',
    dataType:'string',})
    .then(res => {
     console.log(res),

        resjson=res.data.substring(res.data.indexOf('{'),res.data.indexOf('}')+1)
        console.log({"截取后的json":resjson})
        if(''===resjson){
          resjson='{"name":"基金没获取到"}';
        }
        const resJsonFormate=JSON.parse(resjson)
        const fundInfo=
        {
          title: resJsonFormate.name, //基金名称
          upperSubtitle: fundCode, //基金代码
          lowerSubtitle: resJsonFormate.gztime, //估值时间
          titlePosition: 'top',  //表头的位置
          percent:resJsonFormate.gszzl, //估算增长率
          time: resJsonFormate.dwjz, //单位净值
          arrow: false, //列表的箭头
        }
        var fundList=this.data.fundInfoList;
        fundList.push(fundInfo)
        this.setData({
          fundInfoList :fundList,
        })
        if(fundList.length>0){
          this.setData({
            hasFundCode:true,
          })
          
        }
        console.log({"fundCode结束":fundCode})
        resolve(res)
    })
      .catch(error => reject(error));
  });
},

goAddFund(){

my.navigateTo({
  url: '/page/tabBar/addFund/addFund'
});

}
 


});
